package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.customer.dto.response.CommonUserResDTO;
import com.jzo2o.api.customer.dto.response.InstitutionStaffResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.constants.ErrorInfo;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.domain.InstitutionStaff;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {
    @Resource
    private MapApi mapApi;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if (CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    @Override
    public void addAddress(AddressBookUpsertReqDTO dto) {
        //1.参数校验
        if (ObjectUtil.isNull(dto)) {
            throw new CommonException(ErrorInfo.Msg.REQUEST_PARAM_ILLEGAL);
        }
        AddressBook addressBook = new AddressBook();
        BeanUtil.copyProperties(dto, addressBook);
        //2.设置其余必须属性
        addressBook.setUserId(UserContext.currentUser().getId());
        //获取经纬度

        String[] split = dto.getLocation().split(",");
        addressBook.setLon(Double.valueOf(split[0]));
        addressBook.setLat(Double.valueOf(split[1]));
        addressBook.setCreateTime(LocalDateTime.now());
        addressBook.setCreateBy(UserContext.currentUserId());
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBook.setUpdateBy(UserContext.currentUser().getId());
        //3. 判断是否设为默认地址
        if (dto.getIsDefault() == 1) {
            //若为,则把数据库中所有该用户的地址都设置为非默认。
            lambdaUpdate()
                    .set(AddressBook::getIsDefault, 0)
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .update();
        }
        //4.插入数据库
        save(addressBook);
    }

    @Override
    public PageResult<AddressBookResDTO> queryAddressPage(AddressBookPageQueryReqDTO dto) {
        Page<AddressBook> page = PageUtils.parsePageQuery(dto, AddressBook.class);

        LambdaQueryWrapper<AddressBook> queryWrapper = Wrappers
                .<AddressBook>lambdaQuery()
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .orderByDesc(ObjectUtil.isNotEmpty(dto.getIsAsc1()), AddressBook::getIsDefault)
                .orderByDesc(ObjectUtil.isNotEmpty(dto.getIsAsc2()), AddressBook::getUpdateTime);

        Page<AddressBook> addressBookPage = baseMapper.selectPage(page, queryWrapper);
        return PageUtils.toPage(addressBookPage, AddressBookResDTO.class);

    }

    @Override
    public void updateAddress(AddressBookUpsertReqDTO dto,Long id) {
        //1.参数校验
        if (ObjectUtil.isNull(dto)) {
            throw new CommonException(ErrorInfo.Msg.REQUEST_PARAM_ILLEGAL);
        }
        AddressBook addressBook = new AddressBook();
        BeanUtil.copyProperties(dto, addressBook);
        //2.设置其余必须属性
        addressBook.setUserId(UserContext.currentUser().getId());
        //获取经纬度,并设置
        String location = mapApi.getLocationByAddress(dto.getAddress()).getLocation();
        String[] split = location.split(",");
        addressBook.setLon(Double.valueOf(split[0]));
        addressBook.setLat(Double.valueOf(split[1]));
        addressBook.setCreateTime(LocalDateTime.now());
        addressBook.setCreateBy(UserContext.currentUserId());
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBook.setUpdateBy(UserContext.currentUser().getId());
        addressBook.setId(id);
        //3. 判断是否设为默认地址
        if (dto.getIsDefault() == 1) {
            //若为,则把数据库中所有该用户的地址都设置为非默认。
            lambdaUpdate()
                    .set(AddressBook::getIsDefault, 0)
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .update();
        }
        //4.更新数据库
        baseMapper.updateById(addressBook);
    }

    @Override
    public AddressBook getDetail(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void defualt(Integer flag, Long id) {
        //1.参数校验
        if (ObjectUtil.isNull(id) || ObjectUtil.isNull(flag)){
            throw new CommonException(ErrorInfo.Msg.REQUEST_PARAM_ILLEGAL);
        }
        //2.如果是设置默认地址,则先把该用户的所有地址先设置为非默认,然后在修改选中地址为默认
        lambdaUpdate()
                .set(AddressBook::getIsDefault, 0)
                .eq(AddressBook::getUserId, UserContext.currentUserId())
                .update();
        if (flag == 1){
            lambdaUpdate()
                    .set(AddressBook::getIsDefault, 1)
                    .eq(AddressBook::getId, id)
                    .update();
        }

    }

    @Override
    public AddressBook getDefualt() {
        return lambdaQuery().eq(AddressBook::getUserId, UserContext.currentUserId())
                .eq(AddressBook::getIsDefault, 1)
                .one();
    }

}
